import { login, GetRoleBySysUserMenuLists } from '@/api/user'
import { setToken, getToken } from '@/libs/util'

export default {
  state: {
    userName: '',
    userId: '',
    token: getToken(),
    access: ''
  },
  mutations: {
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { userName, password }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({ userName, password }).then(res => {
          const data = res.data.data
          commit('setUserName', data.UserName)
          commit('setUserId', data.Id)
          commit('setToken', data.UserName)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        // logout(state.token).then(() => {
        //   commit('setToken', '')
        //   commit('setAccess', [])
        //   resolve()
        // }).catch(err => {
        //   reject(err)
        // })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setToken', '')
        commit('setAccess', [])
        resolve()
      })
    },
    // 根据角色获取系统菜单
    GetRoleBySysUserMenuLists ({ commit }, token) {
      return new Promise((resolve, reject) => {
        GetRoleBySysUserMenuLists({ UserType: localStorage.getItem('UserType') }).then(res => {
          if (!res.data.success) {
            reject(new Error('获取失败'))
          } else {
            localStorage.setItem('userAccessMenu', res.data.data.map(item => item.Menu_Num))
            commit('setAccess', res.data.data.map(item => item.Menu_Num))
            resolve(res.data.data.map(item => item.Menu_Num))
          }
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
